<template>
	<view>
		<!-- 自定义header -->
		<uni-navbar-lite title="发表文字">
			<!-- <template #right>
				<view class="button uni-row uni-center uni-column" @click="apply" :class="{disabled: disabled}" hover-class="button-hover">
					<text class="text color-white font-14 font-bold">发表</text>
				</view>
			</template> -->
		</uni-navbar-lite>

		<!-- 发表文字 -->
		<view class="content">
			<textarea class="uni-textarea font-16" v-model="content" cursor-color="#29ad68" placeholder="这一刻的想法:" :auto-focus="true" :auto-height="true" :adjust-position="false" :maxlength="100"></textarea>

			<!-- 图片上传 -->
			<uni-drag-image ref="dragImage" :imageList="imageList" @chooseImage="chooseImageEvent"></uni-drag-image>
			<!-- 菜单 -->
			<uni-list>
				<uni-item title="所在位置" icon="location" :value="location.name" @click="setAddress"></uni-item>
			<!-- 	<uni-item title="提醒谁看" icon="eye"></uni-item>
				<uni-item title="谁可以看" icon="staff" value="公开"></uni-item> -->
			</uni-list>
		</view>
		<view class="button uni-row uni-center uni-column" @click="apply" :class="{disabled: disabled}" hover-class="button-hover">
			<text class="text color-white font-14 font-bold">发表</text>
		</view>
	</view>
</template>

<script>
	// import { LocationType } from '@/type/typeData.uts';
	import UniList from '@/components/uni-list/uni-list.vue';
	import UniItem from '@/components/uni-list/uni-item.vue';
	import uniDragImage from '../../components/uni-drag-image/uni-drag-image.vue';
	import uniNavbarLite from '@/components/uni-navbar-lite/uni-navbar-lite.vue';
	// import COS from 'cos-js-sdk-v5'; //引入Cos
	import {
		uploadFile, getCommonToken, uploadFile2
	} from '@/utils/upload.js' //引入方法
    import * as FindApi from '@/api/find'
	export default {
		components: {
			UniList,
			UniItem,
			uniDragImage,
			uniNavbarLite
		},
		data() {
			return {
				disabled: true,
				imageList: [],
                content: '',
				location: {}, // 当前位置信息
				cos: null,
				resources: [], // 选择的图片信息
				txUrl: [], // 上传腾讯云获取的地址
				file_config: {
					size: 50,
					limit: 10,
					title: "",
					headers: {},
					formData: {},
					automatic: false, //是否自动上传
					fileMediatype: "image"
				},
			};
		},
		mounted() {
			// this.getCommonStsToken()
		},
		watch: {
			content: {
				handler(newVal,oldVal) {
					if(newVal) {
						this.disabled = false
					} else{
						this.disabled = true
					}
				},
				deep:true
			}
		},
		methods: {
			setAddress() {
				// if (JSON.stringify(this.location) !== '{}') return;
                const app = this
				uni.showLoading({
					title: '正在获取位置...'
				});
			  // if ("geolocation" in navigator) {
			  //   navigator.geolocation.getCurrentPosition(
			  //     (position) => {
			  //       console.log("Latitude:", position.coords.latitude);
			  //       console.log("Longitude:", position.coords.longitude);
			  //       // 这里你可以处理位置信息，比如发送到服务器等
			  //     },
			  //     (error) => {
			  //       console.error("Error Code = " + error.code + " - " + error.message);
			  //     },
			  //     {
			  //       enableHighAccuracy: true, // 提高获取精度的设置
			  //       timeout: 5000, // 超时时间设置为5000毫秒
			  //       maximumAge: 0 // 缓存时间设置为0，每次都请求新的位置信息
			  //     }
			  //   );
			  // } else {
			  //   console.log("Geolocation is not supported by this browser.");4KQBZ-W5N36-CJKSF-EQQN4-2OXTZ-V4F5J
			  // }
				//#ifdef APP-PLUS || MP-WEIXIN || H5
				uni.getLocation({
					type: 'wgs84', // gcj02
					altitude: true,
					geocode: true,
					success: (res) => {
						console.log('定位成功：', res);
						uni.chooseLocation({
							success: function (result) {
								console.log('位置名称：', result);
								console.log('详细地址：' + result.address);
								console.log('纬度：' + result.latitude);
								console.log('经度：' + result.longitude);
								app.location = {
									latitude:result.latitude,
									longitude:result.longitude,
									name: result.name,
									address: result.address
								}
							}
						});
					},
					fail: (res) => {
						console.log('定位失败：', res);
						this.location = {};
					},
					complete: () => {
						uni.hideLoading();
					}
				});
				//#endif
			},

			// 发表朋友圈
			apply() {
				// this.imageList = [
				// 	"http://iph.href.lu/200x200?text=1&fg=666666&bg=cccccc",
				// 	"http://iph.href.lu/200x200?text=2&fg=666666&bg=cccccc",
				// 	"http://iph.href.lu/200x200?text=3&fg=666666&bg=cccccc",
				// 	"http://iph.href.lu/200x200?text=4&fg=666666&bg=cccccc",
				// 	"http://iph.href.lu/200x200?text=5&fg=666666&bg=cccccc",
				// 	"http://iph.href.lu/200x200?text=6&fg=666666&bg=cccccc",
				// 	"http://iph.href.lu/200x200?text=7&fg=666666&bg=cccccc",
				// 	"http://iph.href.lu/200x200?text=8&fg=666666&bg=cccccc",
				// 	"http://iph.href.lu/200x200?text=9&fg=666666&bg=cccccc",
				// ];
				const app = this
				let obj = {
					"content": this.content,
					"resources": JSON.stringify(this.resources), // json编码一下 地位位置信息
					"iamge": this.txUrl, // 图片资源数组
					"location":JSON.stringify(this.location) // json编码一下 地位位置信息
				}
				console.log('提交发表', obj, this.location)
				FindApi.postsCreate(obj)
				.then(result => {
				    app.$toast('提交成功')
					console.log(result,'result')
					setTimeout(() => app.onNavigateBack(1), 1000)
				})
			},

			// 选择图片
			chooseImageEvent() {
				const count = this.imageList.length > 0 ? 9 - this.imageList.length : this.imageList.length;
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: res => {
						const app = this
						//#ifdef H5
						const filePath = res.tempFiles[0]; // 获取选择的图片路径
						const filePath2 = res.tempFilePaths[0]; // 获取选择的图片路径
						let startIndex = filePath.name.lastIndexOf('.')
						let urls = filePath.name.substring(startIndex);
						//#endif
						// #ifdef APP-PLUS || MP-WEIXIN
						const filePath = res.tempFilePaths[0]; // 获取选择的图片路径
						let startIndex = filePath.lastIndexOf('.')
						let urls = filePath.substring(startIndex);
						//#endif
						const [y, m, d] = [new Date().getFullYear(), String(new Date().getMonth() + 1).padStart(2, '0'), String(new Date().getDate()).padStart(2, '0')];
						const fileName = `images/console/${y}${m}${d}/${Date.now()}_${Math.random().toString(36).substr(2, 6)}${urls}`; // 生成文件名
						console.log(res,filePath,fileName, urls)
						FindApi.commonToken({})
						  .then(result => {
							//#ifdef H5
							uploadFile2(result, filePath,fileName,res.tempFiles[0].size).then(cosRes => {
								console.log(cosRes) // 拿到腾讯云图片地址
								if(cosRes) {
									const startIndex = cosRes.indexOf('/') + 1;
									const urls = cosRes.substring(startIndex);
									app.txUrl = [ ...app.txUrl, urls]
									app.resources = [ ...app.resources, urls]
									app.imageList = [...app.imageList, filePath2];
								}
								app.$toast('上传成功')
							}).catch(err => {
								console.log(err)
							})
							//#endif
							// #ifdef APP-PLUS || MP-WEIXIN
							uploadFile(result, filePath,fileName).then(cosRes => {
								console.log(cosRes) // 拿到腾讯云图片地址
								if(cosRes) {
									const startIndex = cosRes.indexOf('/') + 1;
									const urls = cosRes.substring(startIndex);
									app.txUrl = [ ...app.txUrl, urls]
									app.resources = [ ...app.resources, urls]
									app.imageList = [...app.imageList, filePath];
								}
								app.$toast('上传成功')
							}).catch(err => {
								console.log(err)
							})
							// #endif
						})
					},
				})
			},
			// 获取上传临时密钥
			getCommonStsToken() {
				FindApi.commonToken({})
				  .then(result => {
					getCommonToken(result)
				  })
			},
			
			/**
			 * 登录成功-跳转回原页面
			 */
			onNavigateBack(delta = 1) {
			  const pages = getCurrentPages()
			  if (pages.length > 1) {
			    uni.navigateBack({
			      delta: Number(delta || 1)
			    })
			  } else {
			    this.$navTo('pages/find/index')
			  }
			}
		}
	}
</script>

<style lang="scss" scoped>
	.button {
		height: 75rpx;
		// width: 100rpx;
		margin: 0 56rpx;
		border-radius: 46rpx;
		background: #29ad68;
	}

	.disabled {
		background: #ddd !important;

		.text {
			color: #999;
		}
	}

	.content {
		padding: 30rpx 60rpx;
	}

	.uni-textarea {
		min-height: 300rpx;
	}

	.button-hover {
		background-color: #dedede;
	}
</style>